import { t } from 'i18next'
import { useEffect, useState } from 'react'
import jumpPage from '@/utils/jumpPage'
import { ColumnProps, Modal, Tag } from '@kedacom/react-next'
import { fetchGetPlatformServiceUrl, fetchSetCookie } from '@/api/global'
import { fetchDeleteHistoryMeeting, fetchGetHistoryMeetingList } from '@/api/historyMeeting'
import { HistoryMeetingEntity } from '@/api/historyMeeting/interface'
import { SearchParamsEntity } from './interface'
import dayjs from '@/plugins/dayjs'
import Alert, { confirmModal } from '@/components/Alert'
import { useGlobalStore } from '@/store/global'
import shallow from 'zustand/shallow'

export default function useTemplateService() {
	const [isSearch, setIsSearch] = useState(false)
	const [name, setName] = useState<string>('') /**输入会议名称 */
	const [start_time, setStartTime] = useState<dayjs.Dayjs>(dayjs(new Date()).subtract(7, 'day')) /**开始时间 */
	const [end_time, setEndTime] = useState<dayjs.Dayjs>(dayjs(dayjs(new Date()))) /**开始时间 */
	const [minDate] = useState<dayjs.Dayjs>(dayjs(new Date()).subtract(90, 'day'))
	const [maxDate] = useState<dayjs.Dayjs>(dayjs(new Date()))
	const [data, setData] = useState<Array<HistoryMeetingEntity>>([])
	const [selectedRowIds, setSelectedRowIds] = useState<string[]>([])
	const [pager, setPager] = useState({ page: 1, size: 20, total: 0 })
	const { user, userLoaded, SWITCH } = useGlobalStore(
		(state) => ({
			user: state.user,
			userLoaded: state.userLoaded,
			SWITCH: state.SWITCH,
		}),
		shallow
	)
	const columns: ColumnProps<HistoryMeetingEntity>[] = [
		{
			title: t('名称'),
			dataKey: 'name',
			render: (rowData) => {
				return <span>{rowData.conf_category === 1 ? `[VCS]${rowData.name}` : rowData.name}</span>
			},
		},
		{
			title: t('开始时间'),
			dataKey: 'start_time',
			width: 180,
			render: (rowData) => {
				return <span>{rowData.start_time ? dayjs(rowData.start_time).format('YYYY-MM-DD HH:mm:ss') : ''}</span>
			},
		},
		{
			title: t('结束时间'),
			dataKey: 'end_time',
			width: 180,
			render: (rowData) => {
				return <span>{rowData.end_time ? dayjs(rowData.end_time).format('YYYY-MM-DD HH:mm:ss') : ''}</span>
			},
		},
		{
			title: t('发起人'),
			dataKey: 'creator',
			width: 180,
			render: (rowData) => {
				return <span>{rowData.creator?.name || ''}</span>
			},
		},
		{
			title: t('操作'),
			dataKey: 'action',
			width: 180,
			render: (rowData) => {
				return (
					<>
						<Tag onClick={() => jumpPage('detail', rowData.meeting_id)}>{t('详情')}</Tag>
						{!!SWITCH.meetingSpace && <Tag onClick={() => getMeetingSpace(rowData)}>{t('会议空间')}</Tag>}
					</>
				)
			},
		},
	]
	useEffect(() => {
		if (!userLoaded) return
		if (!user?.enable_meeting) {
			return
		} else {
			loadHistoryMeeting({ start: 0 })
		}
	}, [user, userLoaded])
	/**进入会议空间 */
	const getMeetingSpace = async (rowData: HistoryMeetingEntity) => {
		const { video, meeting_id } = rowData
		if (video == 0) {
			const _url = await fetchGetPlatformServiceUrl()
			fetchSetCookie({ meeting_moid: meeting_id, type: 1 }, function () {
				window.open(_url + `/meeting/meetingSpace/${meeting_id}`)
			})
		} else {
			fetchSetCookie({ meeting_moid: meeting_id, type: 1 }, function () {
				window.open(`/meeting/meeting/meetingSpace/${meeting_id}`)
			})
		}
	}
	const handleDelete = () => {
		if (selectedRowIds.length === 0) {
			Alert(t('请选择历史会议'))
			return false
		}
		let meetingIds = selectedRowIds.join(',')
		confirmModal({
			msg: <div>{t('您确定要删除选择的历史会议吗？')}</div>,
			onOk: async () => {
				const success = await fetchDeleteHistoryMeeting(meetingIds)
				if (success) {
					if (data.length <= selectedRowIds.length) {
						loadHistoryMeeting({ start: Math.max((pager.page - 2) * pager.size, 0) })
					} else {
						loadHistoryMeeting({ start: (pager.page - 1) * pager.size })
					}
					setSelectedRowIds([]) /**清空选中的列表 */
				} else {
					Alert(t('删除失败'))
				}
			},
		})
	}
	const handlePageChange = (pageIndex: number) => {
		loadHistoryMeeting({ start: (pageIndex - 1) * pager.size })
	}
	const handleSearch = () => {
		loadHistoryMeeting({ start: 0 })
		setIsSearch(true)
	}
	const emptyFilter = () => {
		setName('')
		setStartTime(dayjs(new Date()).subtract(7, 'day'))
		setEndTime(dayjs(dayjs(new Date())))
		setIsSearch(false)
		loadHistoryMeeting({
			name: '',
			start_time: dayjs(new Date()).subtract(7, 'day').format(),
			end_time: dayjs(dayjs(new Date())).format(),
			start: 0,
		})
	}
	/**加载历史会议 */
	const loadHistoryMeeting = async (params: Partial<SearchParamsEntity>) => {
		const request_params: SearchParamsEntity = {
			count: pager.size,
			start: 0,
			start_time: dayjs(start_time).format(),
			end_time: dayjs(end_time).add(1, 'day').format(),
			state: 3,
			name: name,
			order: 1,
		}
		let _request_params = Object.assign({}, request_params, params)
		const historyMeetingList = await fetchGetHistoryMeetingList(_request_params)
		if (historyMeetingList && historyMeetingList.success) {
			setData(historyMeetingList.meetings) /**设置数据*/
			// setDataBackup(historyMeetingList.meetings) /**设置备份数据 */
			let total = historyMeetingList.total || 0
			let pageIndex = Math.floor((params.start ?? 0) / pager.size) + 1
			let maxPageNum = total === 0 ? 1 : Math.ceil(total / pager.size)
			if (maxPageNum < pageIndex) {
				setPager({ ...pager, page: maxPageNum, total })
				loadHistoryMeeting({ start: (maxPageNum - 1) * pager.size })
			} else {
				setPager({ ...pager, page: pageIndex, total })
			}
			setSelectedRowIds([]) /**清空选中的列表 */
		}
	}
	return {
		columns,
		pager,
		/**选中的历史会议 */
		selectedRowIds,
		setSelectedRowIds,
		/**切换页码 */
		handlePageChange,
		/**删除历史会议 */
		handleDelete,
		/**搜索的会议名称 */
		name,
		setName,
		/**搜索的开始时间 */
		start_time,
		setStartTime,
		/**搜索结束时间*/
		end_time,
		setEndTime,
		/**是否点击了搜索按钮 */
		isSearch,
		/**清空筛选 */
		emptyFilter,
		/**最小选择时间 */
		minDate,
		/**最大选择时间 */
		maxDate,
		/**搜索历史会议*/
		handleSearch,
		/**数据源 */
		data,
	}
}
